import { Form, Input, Card, Space, Image, Popconfirm, Button, Segmented, Empty } from 'antd';
import { cloneDeep } from 'lodash';

import { CommonButtons } from '@/components/CommonButtons';
import { IconButton, Iconify } from '@/components/icon';
import designEditor from '@/editorComponent/designEditor';
import editorStore from '@/editorComponent/editorStore';
import { useCommon } from '@/hooks/common';
import setEditorDate from '@/pages/editor/setEditorDate';
import { toYuan } from '@/utils/format-number';

export default function CollectPage() {
  const uri = 'collect';
  const {
    data = {},
    searchForm,
    onSearchFormReset,
    onSearch,
    query,
    setQuery,
    doDel,
  } = useCommon({ type: '1', keyword: '' }, uri, {});

  const handleTab = (e: any) => {
    setQuery({ ...query, type: e });
  };

  const onEdit = (row: any) => {
    console.log(row, '去编辑');
  };

  const toUseDesign = async (good: any) => {
    window.location.href = `/#/editor/${good.id}`;
    await setEditorDate();
    const { goodsData, activeComponent } = editorStore;
    const fabricMark = designEditor.fabricMarkMap.get(activeComponent);
    if (goodsData && fabricMark) {
      const component = goodsData.component.find((c) => c.key === activeComponent);
      if (component) {
        const { print_area_left, print_area_top, print_area_width, print_area_height } = component;

        let offsetLeft = 0; // 根据打印位置计算模版元素的偏移量
        let offsetTop = 0;
        let offsetScale = 1;

        // 200mm*265mm 的局部印 和 280mm*350mm的局部印
        if ([200, 280].includes(print_area_width)) {
          offsetScale = print_area_width / fabricMark.sideLength / (400 / 1024);
          offsetLeft =
            ((print_area_left + print_area_width / 2) / fabricMark.sideLength) * 1024 - 200;
          offsetTop =
            ((print_area_top + print_area_height / 2) / fabricMark.sideLength) * 1024 - 265;
          // 满版印就居中
        } else {
          offsetScale = 1;
          offsetLeft = 512 - 200;
          offsetTop = 512 - 265;
        }
        const designData = cloneDeep(JSON.parse(good.designData || "{}"));
        designData.objects.map((o: fabric.Object) => {
          o.left! += offsetLeft;
          o.top! += offsetTop;
          o.scaleX! *= offsetScale;
          o.scaleY! *= offsetScale;
        });
        editorStore.setLoadding(true);
        // 保留底色
        designData.background = designEditor.fabricCanvas.backgroundColor;
        designEditor.clear();
        designEditor.fabricCanvas.loadFromJSON(designData, () => {
          editorStore.setLoadding(false);
        });
      }
    }
    // console.log(row, '使用设计');
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card title="我的收藏" bordered={false}>
        <div className="flex justify-between">
          <Segmented
            defaultValue="1"
            options={[
              {
                value: '1',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    商城商品
                  </div>
                ),
              },
              {
                value: '2',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    素材收藏
                  </div>
                ),
              },
            ]}
            onChange={handleTab}
          />
          <Form layout="inline" form={searchForm} onFinish={onSearch}>
            <Form.Item name="keyword">
              <Input placeholder="产品名称或编号" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={onSearchFormReset}>重置</Button>
            </Form.Item>
          </Form>
        </div>

        <div className="mt-[20px] flex flex-wrap gap-[10px]">
          {data.list?.length ? (
            data.list.map((item: any) => {
              return (
                <div className="relative flex flex-col gap-[10px]" key={item.id}>
                  <div className="relative h-[240px] w-[240px] overflow-hidden">
                    <Image
                      src={item.type === 2 ? item.thumbs : JSON.parse(item.thumbs || '[]')[0]}
                      alt="img"
                      preview={false}
                    />
                    <div className="absolute right-[10px] top-[10px] z-10">
                      <Popconfirm
                        title="确认删除该数据？"
                        okText="确定"
                        cancelText="取消"
                        placement="left"
                        onConfirm={() => doDel(item.id)}
                      >
                        <IconButton>
                          <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
                        </IconButton>
                      </Popconfirm>
                    </div>
                  </div>
                  <div className="flex justify-between">
                    <div className="font-bold">{item.name}</div>
                    {item.type === 2 ? (
                      <IconButton onClick={() => onEdit(item)}>
                        <Iconify icon="solar:pen-bold-duotone" size={18} />
                      </IconButton>
                    ) : (
                      ''
                    )}
                  </div>
                  <div className="flex justify-between text-[#686B73]">
                    <div>ID: {item.targetId}</div>
                    <div>{item.createTime.substr(0, 10)}</div>
                  </div>
                  <div className="flex justify-between">
                    <div className="text-[#fd7901]">￥{toYuan(item.price)}</div>
                    {item.price ? '' : <div className="text-[#35C759]">限时免费</div>}
                  </div>
                  {item.type === 1 ? (
                    <CommonButtons
                      good={{ ...item, id: item.targetId, goodsName: item.name }}
                      edit={item.type === 1}
                      share={item.type === 1}
                      cart={item.type === 1}
                      design={item.type === 2}
                      designTitle="使用该设计"
                    />
                  ) : (
                    <Button type="primary" onClick={() => toUseDesign(item)}>
                      使用此设计
                    </Button>
                  )}
                </div>
              );
            })
          ) : (
            <div className="flex-1">
              <Empty />
            </div>
          )}
        </div>
      </Card>
    </Space>
  );
}
